package com.wtwd.device.handler;


import com.wtwd.device.annotation.MsgType;
import com.wtwd.device.constant.MsgTypeEnum;
import com.wtwd.device.properties.MqProperties;
import com.wtwd.device.rocketMq.MqReceiveMsg;
import com.wtwd.device.rocketMq.MqSendMessage;
import org.reflections.Reflections;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

@Component
public class MsgHandlerFactory {

    private MsgHandlerFactory() {

    }

    private static MqSendMessage sendMessage;

    private static MqReceiveMsg mqReceiveMsg;

    private static IMsgHandler msgHandler;


    // 创建处理类映射关系
    private static final Map<String, Class<? extends ProcessMessageHandler>> msgTypeMsg = new HashMap<>();

    static {
        Reflections reflections = new Reflections("com.wtwd.device");
        Set<Class<?>> annotatedClasses = reflections.getTypesAnnotatedWith(MsgType.class);
        for (Class<?> clazz : annotatedClasses) {
            MsgType annotation = clazz.getAnnotation(MsgType.class);
            if (annotation != null) {
                msgTypeMsg.put(annotation.value().getCmdName(), (Class<? extends ProcessMessageHandler>) clazz);
            }
        }
    }

    //log.info("注册服务:{}", service.getClass().getName());
    public static ProcessMessageHandler createProcessMessageHandler(String msgType) throws InstantiationException, IllegalAccessException {
        // 根据注解值选择相应的类并创建实例
        Class<? extends ProcessMessageHandler> processorClass = msgTypeMsg.get(msgType);
        if (processorClass != null) {
            return processorClass.newInstance();
        } else {
            return msgTypeMsg.get(MsgTypeEnum.APP_GENERAL_CMD.getCmdName()).newInstance();
        }
    }


    public static void initMqService(MqProperties mqProperties) {
        sendMessage = new MqSendMessage(mqProperties);
        mqReceiveMsg = new MqReceiveMsg(mqProperties);
        msgHandler = new MsgHandler();
    }


    public static MqSendMessage getMqSendMessage() {
        return sendMessage;
    }

    public static IMsgHandler getMsgHandler() {
        return msgHandler;
    }
}
